package com.andyliu.interceptor;

import com.andyliu.util.JwtUtil;
import com.andyliu.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * ClassName: LoginInterceptor
 * Description: TODO
 * date: 2021/2/1 11:09 下午
 *
 * @author andyliu
 * @since JDK 1.8
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头（如果有此请求头，表示token已经签发）
        String header = request.getHeader("Authorization");

        if (header != null || !"".equals(header)) {
            //解析请求头（防止伪造token，token内容以"token "作为开头）

                try {
                    Claims c = JwtUtil.parseJWT(header);
                    // 验证成功后刷新token
                    String id = c.getId();
                    String subject = c.getSubject();
                    String token = JwtUtil.createJWT(id,subject,"");
                    System.out.println("*************"+token);
                    response.setHeader("Authorization",token);
                    return true;
                    // 放行请求
                } catch (Exception e) {
                    Result result=Result.error(510,"签名过期");
                    PrintWriter out = response.getWriter();
                    ObjectMapper mapper = new ObjectMapper();
                    String rs = mapper.writeValueAsString(result);
                    out.write(rs);
                    return false;
                }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
